<?php
namespace app\controller;

use app\BaseController;
use app\model\Article;
use app\model\Cast;
use app\model\Movie;
use app\model\MovieClass;
use app\model\MovieCollect;
use app\model\MovieDetail;
use app\model\MoviePics;
use app\model\Review;
use app\model\User;
use OSS\OssClient;
use think\Validate;
use OSS\Core\OssException;

class Index extends BaseController
{
    protected $limit = 5;

    public function movieType(){    //根据类型获取影片
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([   //添加字段验证规则
            'type|影片类型' => 'require|number',
            'page|页数' => 'require|number',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $offset = self::getPage($input['page']);
        $arr = MovieDetail::getListByType($input['type'],$offset,$this->limit);
        $movie_ids = array_column($arr,'movie_id');
        $res = Movie::getList($movie_ids);  //获取movie表的记录
        foreach ($res as $k=>$v){       //获取pics表和review表的记录
            $res[$k]['pics'] = MoviePics::getListByMid($v['id'])->toArray();
            $res[$k]['review'] = Review::getListByMid($v['id'])->toArray();
        }
        if(!empty($res)){
            $this->success('成功',$res);
        }
        $this->error(40001,'数据为空');
    }

    public function ranking(){  //排行榜，按评分降序获取影片列表
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'page|页数' => 'require|number',
        ]);
        if (!$validate->check($input)) {
             return $this->error(40000, $validate->getError());
        }
        $offset = self::getPage($input['page']);
        $res = Movie::getListSortGrade($offset,$this->limit);
        foreach ($res->toArray() as $k=>$v){
            $detail = MovieDetail::getListByMid($v['id']);
            $arr = explode(',',$detail['pics_id']);
            $pics = MoviePics::getList($arr);
//            $arrs = explode(',',$detail['cast_id']);
//            $cast = Cast::getList($arrs);
            $res[$k]['pics'] = $pics->toArray();
//            $res[$k]['cast'] = $cast->toArray();
            $res[$k]['review'] = Review::getListByMid($v['id'])->toArray();
        }
        if(!empty($res)){
            $this->success('成功',$res);
        }
        $this->error(40001,'数据为空');
    }

    public function movieSearch(){  //搜索影片，按标题
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'title|影片标题' => 'require',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $res = Movie::movieSearch($input['title']);
        if(!empty($res)){
            $this->success('成功',$res);
        }
        $this->error(40001,'数据为空');
    }

    public function isCollect(){    //收藏功能
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'uid|用户id' => 'require|number',
            'movie_id|电影id' => 'require|number',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $where = ['user_id'=>$input['uid'],'movie_id'=>$input['movie_id']];
        $collect = MovieCollect::isCollect($where);
        if(empty($collect)){
            $movie_collect = new MovieCollect();
            $movie_collect->save(['user_id'=>$input['uid'], 'movie_id'=>$input['movie_id'],'is_collect'=>1]);
        }else{
            $collect['is_collect'] == 0 ? $is_collect=1 : $is_collect=0;
            $collect->save(['is_collect'=>$is_collect]);
        }
        $this->success('成功');
    }

    public function isCollectStatus(){  //收藏状态
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'uid|用户id' => 'require|number',
            'movie_id|电影id' => 'require|number',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $where = ['user_id'=>$input['uid'],'movie_id'=>$input['movie_id']];
        $res = MovieCollect::isCollect($where);
        if(empty($res)){
            $res['is_collect'] = 0;
        }
        $this->success('cg',['collect'=>$res['is_collect']]);

    }

    public function movieInfo(){    //获取影片详情
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'id|影片id' => 'require|number',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $res = Movie::getListById($input['id']);
        $detail = MovieDetail::getListByMid($input['id']);
        $arr_detail = explode(',',$detail['pics_id']);
        $res['pics'] = MoviePics::getList($arr_detail)->toArray();
        $arr_cast = explode(',',$detail['cast_id']);
        $res['cast'] = Cast::getList($arr_cast)->toArray();
        $review = Review::getListByMid($input['id'])->toArray();
        foreach ($review as $k => $v){
            $review[$k]['user_info'] = User::getInfo($v['user_id']);
        }
        $res['review'] = $review;
        $this->success('成功',$res);
    }

    public function getClass(){
        $res = MovieClass::getList();
        $this->success('成功',$res);
    }

    public function getMovieByClassId(){
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'class_id|分类id' => 'require|number',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $movie = MovieDetail::getListByClass($input['class_id']);
        $arr = array_column($movie,'movie_id');
        $data = Movie::getList($arr);
        $this->success('成功',$data);
    }


    public function getArticleList(){
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'page|页数' => 'require|number',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $offset = 0;
        if($input['page']>0){
            $offset = $input['page'] * 10;
        }
        $res = Article::getList($offset);
        foreach ($res as $k=>$v){
            $res[$k]['user_info'] = User::getInfo($v['user_id'])->toArray();
        }

        $this->success('成功',$res);
    }

    public function getArticleInfo(){
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'id|文章id' => 'require|number',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $res = Article::getInfoById($input['id']);

        $this->success('成功',$res);
    }

    public function myCollect(){
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'uid|用户id' => 'require|number',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $res = MovieCollect::getInfoByUid($input['uid']);
        $ids = array_column($res->toArray(),'movie_id');
        $data = Movie::getList($ids);
        $this->success('成功',$data);
    }

    public function addReview(){
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'grade|评分' => 'require',
            'uid|用户id' => 'require|number',
            'movie_id|电影id' => 'require|number',
            'content|评价内容' => 'require',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $review = new Review();
        $data = [
            'user_id'=> $input['uid'],
            'movie_id'=>$input['movie_id'],
            'content'=>$input['content'],
            'grade'=>$input['grade'],
            'time'=>time()
        ];
        $review->save($data);
        $this->success('成功');
    }

    public function login(){
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'user_name|用户名' => 'require',
            'pwd|密码' => 'require',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $where = ['user_name'=>$input['user_name'],'user_pwd'=>$input['pwd']];
        $res = User::getInfoByPwd($where);
        if(empty($res)){
            $this->error(40001,'账号或密码错误');
        }
        $this->success('cg',$res);
    }

    public function register(){
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'user_name|用户名' => 'require',
            'pwd|密码' => 'require',
            'name|昵称'=>'require',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $where = ['user_name'=>$input['user_name']];
        $is_user = User::getInfoByPwd($where);
        if(!empty($is_user)){
            $this->error(40002,'该用户已存在');
        }
        $user = new User();
        $data = [
            'user_name'=>$input['user_name'],
            'user_pwd'=>$input['pwd'],
            'name'=>$input['name']
        ];
        $user->save($data);
        $this->success('注册成功');
    }

    public function post(){
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'uid|用户id' => 'require',
            'title|标题' => 'require',
            'content|内容' => 'require',
            'img|图片'=>'require',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $data = [
            'user_id'=>$input['uid'],
            'title'=>$input['title'],
            'content'=>$input['content'],
            'img_url'=>$input['img'],
            'time'=>time(),
            'like'=>0
        ];
        $article = new Article();
        $article->save($data);
        $this->success('发帖成功');
    }


    public function uploadImg(){
        $file = $_FILES['img'];
        $fileName = $file['name'];
        $movFile = $file['tmp_name'];
        $localPath = public_path().$fileName;
        move_uploaded_file($movFile,$localPath);
        $url = $this->upload($fileName);
        $this->success('cg',['url'=>$url]);
    }

    public function userInfo(){
        $input = $this->request->all();
        $validate = new Validate();
        $validate->rule([
            'uid|用户id' => 'require',
        ]);
        if (!$validate->check($input)) {
            return $this->error(40000, $validate->getError());
        }
        $user = User::getInfo($input['uid']);
        $article = Article::getInfoByUid($input['uid']);
        $this->success('发帖成功',['userInfo'=>$user,'article'=>$article]);
    }



    public function getPage($page){
        $offset = 0;
        if($page>0){
            $offset = $page * $this->limit;
        }
        return $offset;
    }

    /**
     * 上传文件
     * @param string $fileName 文件目录
     * @return false|string
     */
    public function upload($fileName = '')
    {
        $fileName = ltrim($fileName, "/");
        if ($fileName) {
            $accessKeyId = env("oss.appid");//去阿里云后台获取秘钥
            $accessKeySecret = env("oss.secret");//去阿里云后台获取秘钥
            $endpoint = env("oss.url");//你的阿里云OSS地址
            $bucket = env("oss.bucket");//你的阿里云OSS地址
//            $domain          = 'oss.aiyunlu.cn';            // 绑定域名
            $keepFile        = '0';         // 保留本地文件

            $object          = 'user/'.$fileName;                    // 设置文件名称
            $filePath        = app()->getRootPath() . 'public/' . $fileName; // 由本地文件路径加文件名包括后缀组成，如/users/local/myfile.txt

            try {
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                // 文件上传
                $result = $ossClient->uploadFile($bucket, $object, $filePath);
                $url = $result['info']['url'];

                // 删除本地文件
                if ($keepFile === '0') {
                    unlink($filePath);
                }
                return $url;
            } catch (OssException $e) {
                return json_encode([
                    'error' => 1,
                    'msg'   => $e->getMessage(),
                    'data'  => '',
                ]);
            }
        }
    }


}
